package org.lazycoder.logger.iface;

import javax.swing.table.AbstractTableModel;

import org.lazycoder.database.Table;

/**
 * An abstract table model.
 * 
 * @author Matthew Bayliss
 */
public class SwingTableModel extends AbstractTableModel {
	private static final long	serialVersionUID	= 7277057374889902755L;
	protected Table				table;
	private boolean				active				= false;
	int							rows				= 0;
	int							cols				= 0;

	public void setTable(Table t) {
		table = t;
		if (table != null) {
			active = true;
		} else {
			active = false;
		}
		fireTableStructureChanged();
	}

	@Override
	public int getColumnCount() {
		if (active) {
			cols = table.getCols();
			return table.getCols();
		} else {
			return 0;
		}
	}

	@Override
	public String getColumnName(int column) {
		if (active) {
			return table.getFriendlyName(column + 1);
		} else {
			return String.valueOf(column);
		}
	}

	@Override
	public int getRowCount() {
		if (active) {
			rows = table.getRows();
			return table.getRows();
		} else {
			return 0;
		}
	}

	@Override
	public Object getValueAt(int arg0, int arg1) {
		if (active) {
			return table.getElement(arg0, arg1);
		} else {
			return 0;
		}
	}

	/**
	 * Update the data in the table to reflect this new table.
	 * 
	 * @param table
	 *            the table with new data
	 */
	public void update() {
		if (active) {
			table.update();
			fireTableRowsInserted(rows, getRowCount());
		}
	}
}
